package com.atguigu.fink.chapter01.sql;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/11/28 09:06
 */
public class Flink04_SQL_Kafka_Upsert {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 1. 建立一个动态与 kafka 的 topic 关联
        tEnv.executeSql("create table sensor(" +
                            "id string, " +
                            "ts bigint, " +
                            "vc int" +
                            ")with(" +
                            "  'connector' = 'kafka', " +
                            "  'topic' = 's1', " +
                            "  'properties.bootstrap.servers' = 'hadoop162:9092', " +
                            "  'properties.group.id' = 'atguigu', " +
                            "  'scan.startup.mode' = 'latest-offset', " +
                            "  'format' = 'csv' " +
                            ")");
    
        Table result = tEnv.sqlQuery("select id, sum(vc) vc_sum from sensor group by id");
    
        tEnv.executeSql("create table sensor_t(" +
                            "id string, " +
                            "vc_sum int," +
                            // flink 没有自己的数据, 所以无法对主键进行是否重复的判断
                            "primary key(id) not enforced " +
                            ")with(" +
                            " 'connector' = 'upsert-kafka', " +
                            "  'topic' = 's3', " +
                            "  'properties.bootstrap.servers' = 'hadoop162:9092', " +
                            "  'key.format' = 'json', " +
                            "  'value.format' = 'json'" +
                            ")");
    
        result.executeInsert("sensor_t");
    
    
    }
}
